package com.hq.common.scheduler;

import com.hq.common.domain.MailSender;
import com.hq.common.utils.MailSenderFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.List;

/**
 * Created by He Zhijie on 2015/7/19.
 */
@Component
public class SendMailJob implements Job {
    public static final String MAIL_TO_LIST = "MAIL_TO_LIST";
    public static final String MAIL_SUBJECT = "MAIL_SUBJECT";
    public static final String MAIL_CONTENT = "MAIL_CONTENT";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getTrigger().getJobDataMap();
        Object mailToList = jobDataMap.get(MAIL_TO_LIST);
        if (mailToList == null) {
            return;
        }
        MailSender mailSender = MailSenderFactory.getInstance();
        try {
            if (mailToList instanceof List) {
                List<String> recipientList = (List<String>) mailToList;
                mailSender.send(recipientList, jobDataMap.getString(MAIL_SUBJECT), jobDataMap.get(MAIL_CONTENT));
            } else if (mailToList instanceof String) {
                mailSender.send(String.valueOf(mailToList), jobDataMap.getString(MAIL_SUBJECT), jobDataMap.get(MAIL_CONTENT));
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static String getJobName(){
        return "SendMailJob";
    }
}
